package com.miao.im.service.friend;

import com.miao.im.domain.FriendDo;
import com.miao.im.domain.UserDo;
import com.miao.im.dto.FriendRespDto;
import com.miao.im.repository.IFriendRepository;
import com.miao.im.repository.dao.IFriendDao;
import com.miao.im.repository.dao.IUserDao;
import com.miao.im.support.exception.BizException;
import com.miao.im.support.page.Page;
import com.miao.im.support.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/4/13 15:43
 * @Description:
 */
@Service
public class FriendService implements IFriendService {
    @Autowired
    private IFriendRepository friendRepository;
    @Autowired
    private IFriendDao friendDao;
    @Autowired
    private IUserDao userDao;

    @Override
    public Page<List<FriendRespDto>> getMyFriendPage(Long userId, Integer pageNum, Integer pageSize) {
        Page<List<FriendDo>> page = friendRepository.getByUserIdPage(userId, pageNum, pageSize);
        List<FriendRespDto> dtos = page.getData().stream().map(this::convert2Dto).collect(Collectors.toList());
        return PageUtil.copyPage(page, dtos);
    }

    @Override
    public void add(Long userId, String username) {
        UserDo userDo = userDao.getByUsername(username)
                .orElseThrow(() -> new BizException("用户不存在"));
        friendDao.getOneByUserIdAndFriendId(userId,userDo.getId()).ifPresent(friendDo -> {
            throw new BizException("好友已存在");
        });
        FriendDo friendDo = new FriendDo(userId, userDo.getId());
        friendDao.insert(friendDo);
    }

    private FriendRespDto convert2Dto(FriendDo f) {
        FriendRespDto respDto = new FriendRespDto();
        respDto.setFriendId(f.getFriendId());
        UserDo friend = f.getFriend();
        respDto.setFriendAvatar(friend.getAvatar());
        respDto.setFriendNickname(friend.getNickname());
        respDto.setFriendUsername(friend.getUsername());
        return respDto;
    }

}
